package com.csj.mvvmtest.notification

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.csj.mvvm.bean.NotifyEntity
import com.csj.mvvm.utils.IntentExtras
import com.csj.mvvm.utils.LogUtil
import com.csj.mvvmtest.BuildConfig
import com.csj.mvvmtest.ui.demo.MsgDetailActivity
import com.csj.mvvmtest.ui.MainActivity


class NotificationReceiver: BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val notify =
            intent.getSerializableExtra(IntentExtras.APS_DATA) as NotifyEntity?
        // 程序未启动
        if (3 == getAppStatus(context, BuildConfig.APPLICATION_ID)) {
            //如果app进程已经被杀死，先重新启动app，将DetailActivity的启动参数传入Intent中，参数经过
            //SplashActivity传入MainActivity，此时app的初始化已经完成，在MainActivity中就可以根据传入
            //参数跳转到DetailActivity中去了
            LogUtil.e("getAppStatus", "NoOpen")
            val launchIntent: Intent? =
                context.packageManager.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID)
            launchIntent?.flags =
                Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
            val bundle = intent.extras
            bundle!!.putBoolean(IntentExtras.KILL, true)
            launchIntent?.putExtra(IntentExtras.IS_NEW_OPEN, bundle) //将信息传给SplashActivity
            context.startActivity(launchIntent)
        } else {
            LogUtil.e("getAppStatus", "Open")
            // 程序启动
            //如果存活的话，就直接启动DetailActivity，但要考虑一种情况，就是app的进程虽然仍然在
            //但Task栈已经空了，比如用户点击Back键退出应用，但进程还没有被系统回收，如果直接启动
            //DetailActivity,再按Back键就不会返回MainActivity了。所以在启动
            //DetailActivity前，要先启动MainActivity。
            val mainIntent = Intent(context, MainActivity::class.java)
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)

            //是否跳转不同detailIntent
            val detailIntent = Intent(context, MsgDetailActivity::class.java)
            val intents: Array<Intent>
            intents = arrayOf(mainIntent, detailIntent)
            context.startActivities(intents)
        }
    }

    /**
     * 返回app运行状态
     * 1:程序在前台运行 //
     * 2:程序在后台运行//
     * 3:程序未启动 注意：需要配置权限//
     * <uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
     */
    private fun getAppStatus(context: Context, pageName: String): Int {
        return try {
            val am =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val list = am.getRunningTasks(20)
            // 判断程序是否在栈顶 [ ]
            if (list[0].topActivity!!.packageName == pageName) {
                1
            } else {
                // 判断程序是否在栈里
                for (info in list) {
                    if (info.topActivity!!.packageName == pageName) {
                        return 2
                    }
                }
                3 // 栈里找不到，返回3
            }
        } catch (e: Exception) {
            3
        }
    }

}